The readLine()
method.
The readLine()
method reads a line of text from
a character-oriented input stream,
and puts it into a String object
which it returns as a reference.
If there is no more data in the file,
it returns null
.
import java.io.*; class ReadTextFile { public static void main ( String[] args ) { String fileName = "reaper.txt" ; String line; try { BufferedReader in = new BufferedReader( new FileReader( fileName ) ); line = in.readLine(); while ( line != null ) // continue until end of file { System.out.println( line ); line = in.readLine(); } in.close(); } catch ( IOException iox ) { System.out.println("Problem reading " + fileName ); } } }
The file "reaper.txt" is opened for reading
when the
FileReader
stream is constructed.
If the file does not exist in the current directory,
an IOException is thrown.
Next, the program reads each line of the file and writes
it to the monitor.
When end-of-file is detected the program quits.
This is an extremely common programming pattern: reading and processing data until end-of-file. It would be worth while to play with this program. Create "reaper.txt" with Notepad if it does not already exist.